﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Toolkit;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Graphics;
using ESRI.ArcGIS.Client.Tasks;
using System.ServiceModel;
using System.Threading;
using System.Windows.Browser;
using SLMapApp.ServiceReference2;

namespace SLMapApp
{
    public partial class MainPage : UserControl
    {
        GraphicsLayer graphicsLayer;

      
        ESRI.ArcGIS.Client.Tasks.FeatureSet featureSetQuery;//图层要素集 查询选择对象

        public static string SelectedCityname;
        public string telNumber = null;
        public static string mapIp = "";
        ServiceClient proxy = new ServiceClient();//为了方便读取配置文件 统一用一个服务代理对象
        public MainPage()
        {
            InitializeComponent();
            ComboBoxItem lbi = new ComboBoxItem();
            lbi.SetValue(ComboBoxItem.ContentProperty, "---请选择---");
            SelectedCity.Items.Add(lbi);
            SelectedCity.SelectedItem = lbi;
            
            //mapIp = proxy.GetMapIp();
            //ArcGISTiledMapServiceLayer ag = this.myMap.Layers["BaseMapLayer"] as ArcGISTiledMapServiceLayer;
            //ag.Url = mapIp;

           // string uid= HtmlPage.Document.GetProperty("uid").ToString().Trim() ;
            //ShowQueryString();
            string uid="";
            string[] cookies = HtmlPage.Document.Cookies.Split(';');
            if (cookies.Length > 0)
            {
                foreach (string cookie in cookies)
                {
                    string[] keyValues = cookie.Split('=');
                    if (keyValues[0].Trim() == "uid")
                    {
                        uid = keyValues[1].Trim();
                        break;
                    }
                }
            }
            //int length = uid.Length;
            if (uid != "")
            {
              GetUserAuth(uid);
            }

            
        }


        
        /// <summary>
        /// 改变下拉框 重新加载数据 渲染地图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectedCity_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
           //string name = "中牟县";
           //string value = "100002";
           //渲染1绿色，0红色
           if (SelectedCity.SelectedIndex != 0 && SelectedCity.SelectedIndex!=-1)
           {
               graphicsLayer = myMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
               if (graphicsLayer.Graphics != null)
               {
                   graphicsLayer.Graphics.Clear();
               }
               string name = ((SelectedCity.SelectedItem as UserAuth).Name).ToString().Trim(); 
               // name.EndsWith
               //int length = name.Length; //为了和数据库做对应，将县 市这两个字去掉。
               //if (name.EndsWith("县") || name.EndsWith("市"))
               //{
               //    name = name.Substring(0, length - 1);
               //}
               
               string value = (SelectedCity.SelectedItem as UserAuth).OrganId;
               GetOnlineStatus(name, value);
               ClipMaps(name, value);
           }
           //else 
           //{
           //    MessageBox.Show("请选中要查询的区域！");
           //}

        }
        /// <summary>
        /// 服务中取值
        /// </summary>
        private void GetUserAuth(string uid)
        {
            //WebServiceForMapSoapClient wsClient = new WebServiceForMapSoapClient();
            //proxy.GetUserAuthCompleted += new EventHandler<GetUserAuthCompletedEventArgs>(wsClient_GetUserAuthCompleted);
            //proxy.GetUserAuthAsync(uid);
            proxy.GetUserAuthCompleted += new EventHandler<GetUserAuthCompletedEventArgs>(wsClient_GetUserAuthCompleted);
            proxy.GetUserAuthAsync(uid);

        }

        void wsClient_GetUserAuthCompleted(object sender, GetUserAuthCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                for (var i = 0; i < e.Result.Count; i++)
                {
                    SelectedCity.Items.Add(e.Result[i]);
                }

                SelectedCity.DisplayMemberPath = "Name";
                // SelectedCity.Items.Add("中牟县");
            }
           
        }
#region 点图层渲染
        /// <summary>
        /// 获取和下拉框对应的数据
        /// </summary>
        private void GetOnlineStatus(string name, string value)
        {
           // WebServiceForMapSoapClient wsClient = new WebServiceForMapSoapClient();
            proxy.GetOnlineStatusCompleted += new EventHandler<GetOnlineStatusCompletedEventArgs>(wsClient_GetOnlineStatusCompleted);
            proxy.GetOnlineStatusAsync(name, value);
        }
        /// <summary>
        /// 获取数据后，渲染图层
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void wsClient_GetOnlineStatusCompleted(object sender, GetOnlineStatusCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                for (int i = 0; i < e.Result.Count; i++)
                {
                    double pointx = (double)(e.Result[i].ELng);
                    double pointy = (double)(e.Result[i].ELat);
                    Graphic graphiconline = new Graphic();
                    graphiconline.Geometry = new MapPoint(pointx, pointy);
                    if (e.Result[i].EOnline.ToString() == "1")
                    {
                        graphiconline.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol2"] as Symbol;
                        //graphiconline.Attributes["状态"] = "在线";
                    }
                    else if (e.Result[i].EOnline.ToString() == "0")
                    {
                        graphiconline.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as Symbol;
                        //graphiconline.Attributes["状态"] = "离线";
                    }
                    graphiconline.Attributes["NAME"] = e.Result[i].EVillage.ToString();
                    graphiconline.Attributes["SimNo"] = e.Result[i].ESimNo.ToString();
                    graphiconline.Attributes["ENO"] = e.Result[i].ENo.ToString();
                    graphicsLayer.Graphics.Add(graphiconline);
                    graphiconline.MouseLeftButtonDown +=new MouseButtonEventHandler(graphiconline_MouseLeftButtonDown);
                    graphiconline.MouseLeftButtonUp+=new MouseButtonEventHandler(graphiconline_MouseLeftButtonUp);
                }
                MyMapTip.GraphicsLayer = graphicsLayer;
            }
            else
            {
                MessageBox.Show("没有符合条件的数据！");
            }
        }
        /// <summary>
        /// 位弹出框提取信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void graphiconline_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
           // 鼠标左键，显示ToolTip信息  
                        Graphic g = sender as Graphic;
                        if (g != null)
                        {
                            string name= g.Attributes["NAME"].ToString();
                            string ENum = g.Attributes["ENO"].ToString();
                            double height = Application.Current.Host.Content.ActualHeight;
                            double width = Application.Current.Host.Content.ActualWidth;
                            //弹出对应的提示信息   
                            MessageSend tip = new MessageSend(name, ENum);
                            tip._placeName = name;
                            tip._UserTel = ENum;
                            Point p = e.GetPosition(LayoutRoot);
                            if (width - p.X < 400)
                            {
                                p.X = width - 400;
                            }
                            if (height - p.Y < 300)
                            {
                                p.Y = height - 300;
                            }
                            p.X = p.X;
                            p.Y = p.Y;
                            tip.Show(p);
                        }
        }
        private void graphiconline_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

#endregion

#region  查询出所选区域的范围，并放大到此范围
        public void ClipMaps(string name, string value)
        {

            ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query()
            {
                //Geometry = myMap.Extent,
                ReturnGeometry = true,
                OutSpatialReference = myMap.SpatialReference
            };
            query.OutFields.Add("*");
            int length = value.Length;
            switch (length)
            {
                case 2:
                    query.Where = "NAME = '"+name+"'";
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://218.28.143.250:59993/ArcGIS/rest/services/map8/MapServer/9");
                    queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
                    queryTask.ExecuteAsync(query);
                    break;
                case 4:
                    query.Where = "NAME = '" + name + "'";
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask1 = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://218.28.143.250:59993/ArcGIS/rest/services/map8/MapServer/7");
                    queryTask1.ExecuteCompleted += QueryTask_ExecuteCompleted;
                    queryTask1.ExecuteAsync(query);
                    break;
                case 6:
                    query.Where = "NAME = '" + name + "'";
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask2 = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://218.28.143.250:59993/ArcGIS/rest/services/map8/MapServer/10");
                    queryTask2.ExecuteCompleted += QueryTask_ExecuteCompleted;
                    queryTask2.ExecuteAsync(query);
                    break;
                default:
                    break;
            }
        }
     //  ============================
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            if (args.FeatureSet.Features.Count > 0)
            { 
                ESRI.ArcGIS.Client.Tasks.FeatureSet featureSet = args.FeatureSet;
                featureSetQuery = args.FeatureSet;
                this.myMap.ZoomTo(featureSet.Features[0].Geometry);
            }
            else
            { 
               //此处不做任何处理
            }
            
        }
#endregion
#region 定位到村模块
        /// <summary>
        ///定位查询查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.CountyName.Text.ToString().Trim()!= null)
            {
                QueryTask queryTask =
               new QueryTask("http://218.28.143.250:59993/ArcGIS/rest/services/map8/MapServer/0");
                queryTask.ExecuteCompleted += QueryTask_ExecuteCompletedposition;
                queryTask.Failed += QueryTask_Failed;

                ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query();
                query.Text = this.CountyName.Text.ToString().Trim();
                query.OutFields.Add("*");
                queryTask.ExecuteAsync(query);
            }
            else
            {
                MessageBox.Show("请输入要查询的名称！");
            }
            
        }

        /// <summary>
        /// 定位查询完后所激发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void QueryTask_ExecuteCompletedposition(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            GraphicsLayer graLayer = myMap.Layers["MyGraphicsLayerflare"] as GraphicsLayer;
            graLayer.Graphics.Clear();
            FeatureSet featureSet = args.FeatureSet;
            if (featureSet != null && featureSet.Features.Count > 0)
            {
                  string Mname = this.CountyName.Text.ToString().Trim();
                  int Mnamelength = Mname.Length;
                  foreach (Graphic feature in graphicsLayer.Graphics)
                  {
                       string str = feature.Attributes["NAME"].ToString();
                       int strlength = str.Length;
                       if (Mnamelength < strlength)
                       {
                            str = str.Substring(0, Mnamelength);
                       }
                       if ( Mname == str)
                       { 
                           feature.Symbol = LayoutRoot.Resources["SelectMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                           myMap.PanTo(feature.Geometry);
                           return;
                        }
                  }   
            }
            else
            {
                MessageBox.Show("请输入有效的名称或者没有相应的有效数据！");  
            }
        }
        /// <summary>
        /// 查询失败 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void QueryTask_Failed(object sender, TaskFailedEventArgs args)
        {
            MessageBox.Show("Query execute error: " + args.Error);
        }
#endregion
#region  常用工具处理
        //Toolbar点击
        private void Toolbar_ToolbarItemClicked(object sender, ESRI.ArcGIS.Client.Toolkit.SelectedToolbarItemArgs e)
        {
            switch (e.Index)
            {
                case 0:
                   
                    return;

                case 1:
                    //List<string> selectedGraPoint = new List<string>();
                    //if (graphicsLayer.Graphics.Count > 0)
                    //{
                    //    for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                    //    {
                    //        selectedGraPoint.Add(graphicsLayer.Graphics[i].Attributes["NAME"].ToString());
                    //    }
                    //    //this.CountyName.ItemsSource = selectedGraPoint;
                       
                    //}
                    //else
                    //{
                    //    MessageBox.Show("所选地区没有任何村庄，为选中任何地区！");
                    //}
                    if (this.ResultsDisplayCanvas.Visibility == Visibility.Visible)
                    {
                        this.ResultsDisplayCanvas.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        this.ResultsDisplayCanvas.Visibility = Visibility.Visible;
                    }
                    return;

                case 2:
                    //GetOnlineStatus("中牟县","100002");//=================================
                    return;

                case 3:
                    return;

                case 4:
                    Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
                    return;

            }
        }
#endregion


    }
}
